<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理结构 -->
      <div class="role-operate">
        <el-button @click="showDialog = true" size="mini" type="primary"
          >添加角色</el-button
        >
      </div>
      <!-- element表格组件 -->
      <el-table :data="list">
        <el-table-column prop="name" align="center" label="角色" width="200">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            ></el-input>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" label="启用" width="200">
          <!-- 通过作用域插槽定制内容 -->
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
            <span v-else>
              {{
                row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              size="mini"
              type="textarea"
            ></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button @click="btnEditOk(row)" type="primary" size="mini"
                >确定</el-button
              >
              <el-button @click="row.isEdit = false" size="mini"
                >取消</el-button
              >
            </template>
            <template v-else>
              <el-button size="mini" type="text">分配权限</el-button>
              <el-button @click="btnEditRow(row)" size="mini" type="text"
                >编辑</el-button
              >
              <el-popconfirm
                title="确认删除该行数据？"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="text"
                  style="margin-left: 10px"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
            <!-- 按钮转a链接 -->
          </template>
        </el-table-column>
      </el-table>
      <!-- element分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 放置弹层 -->
    <el-dialog
      width="500px"
      title="新增角色"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <!-- 角色状态转换按钮 -->
        <el-form-item label="是否启用" prop="state">
          <!-- 重置表单数据 需要prop属性 -->
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <!-- 角色描述输入框 -->
        <el-form-item prop="description" label="角色描述">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            style="width: 300px"
            size="mini"
          />
        </el-form-item>
        <!-- 确定取消按钮 -->
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk"
                >确定</el-button
              >
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updataRole ,deleteRole} from "@/api/role";
export default {
  name: "Role",
  data() {
    return {
      list: [],
      /* 添加角色弹窗 */
      showDialog: false,
      /* 添加角色相关属性 */
      roleForm: {
        name: "",
        description: "",
        state: 0, // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
      /* 设置分页相关属性 */
      pageParams: {
        page: 1, //第几页
        pagesize: 5, //每页显示多少条
        total: 0,
      },
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams);
      this.list = rows;
      this.list.forEach((item) => {
        //row.isEdit = false; 直接操作数组是不具有响应式
        this.$set(item, "isEdit", false);
        //设置一个新对象作为编辑的缓存空间
        this.$set(item, "editRow", {
          name: item.name,
          description: item.description,
          state: item.state,
        });
      }); //给每一行数据设置一个编辑属性
      this.pageParams.total = total;
    },
    changePage(newPage) {
      this.pageParams.page = newPage; //更新当前页面
      this.getRoleList(); //重新获取数据
    },
    btnOk() {
      this.$refs.roleForm.validate(async (isOk) => {
        if (isOk) {
          await addRole(this.roleForm);
          this.$message.success("新增角色成功");
          this.btnCancel();
          this.getRoleList();
        }
      });
    },
    btnCancel() {
      /* 清空表单关闭弹窗 */
      this.$refs.roleForm.resetFields(); // 重置表单数据
      this.showDialog = false; // 关闭弹层
    },
    /* 点击行内编辑按钮 */
    btnEditRow(row) {
      row.isEdit = true;
      //点击编辑按钮，将缓存对象中的数据回显
      row.editRow.name = row.name;
      row.editRow.state = row.state;
      row.editRow.description = row.description;
    },
    /* 点击更新的确定取消按钮 */
    async btnEditOk(row) {
      if (row.editRow.name && row.editRow.description) {
        await updataRole({ id: row.id, ...row.editRow });
        this.$message.success("更新角色成功");
        //方法一：重新调用接口访问数据库
        /* row.isEdit = false;
        this.getRoleList(); */
        //方法二：直接修改数据
        /* row.name = row.editRow.name;
        row.state = row.editRow.state;
        row.description = row.editRow.description;
        row.isEdit = false; */
        //方法三：使用set方法
        /* this.$set(row, "name", row.editRow.name);
        this.$set(row, "state", row.editRow.state);
        this.$set(row, "description", row.editRow.description);
        row.isEdit = false;
        this.getRoleList(); */
        //方法四：使用assign对象拼接
        Object.assign(row, {
          ...row.editRow,
          isEdit: false,
        });
      } else {
        this.$message("warning", "不能为空");
      }
    },
    /* 非编辑状态下点击删除一行数据 */
    async confirmDel(id) {
      await deleteRole(id);
      this.$message.success( '删除角色成功')
      //如果删除的是当前页的最后一条数据，则需要页面减一并重新渲染页面
      //以上删除操作为调用接口后的后端数据删除，前端页面还未渲染数据,所以当数据只剩一条时，意味着后端一加删完了该页数据
      if (this.list.length===1) {
        this.pageParams.page--
        this.getRoleList();
      }
    },
  },
};
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
